/*eslint-disable*/
const isObj = a => Object.prototype.toString.call(a) === '[object Object]'
const isNum = a => typeof a === 'number'
const isStr = a => typeof a === 'string'
const isArr = a => Array.isArray(a)
const omit = (a, keys) => {
    if (!isObj(a)) return {}
    let _obj = {}
    for (let k in a) {
        if (keys.includes(k)) continue
        _obj[k] = a[k]
    }
    return _obj
}


/* 
DIMENSION: sample2.dxf
*/
const pointTypes = ['POINT', 'TEXT', 'INSERT', 'CIRCLE', 'ARC', 'SEQEND']
const lineStringTypes = ['LINE', 'POLYLINE', 'LWPOLYLINE']
const polygonTypes = ['POLYGON']

// 将dxfjson转geojson
function toGeojson(json) {
    if (!isObj(json)) json = {}
    if (!isArr(json.entities)) json.entities = []

    /* geometry.type:
    Point 1
    MultiPoint 2
    LineString 2
    MultiLineString 3
    Polygon 3
    MultiPolygon 4
    */
    /* properties
    stroke
    stroke-opacity
    stroke-width
	
    fill
    fill-opacity
    */
    const fmtFeature = a => {
        if (!isObj(a)) a = {}
        let properties = {}
        let type = null
        let coordinates = []

        if (pointTypes.includes(a.type)) {
            let { x, y, z } = a.startPoint || a.position || a.center || {}
            properties = omit(a, ['startPoint', 'position', 'center'])
            type = 'Point'
            coordinates = [x, y, z || 0]
        } else if (lineStringTypes.includes(a.type) && isArr(a.vertices)) {
            const { color = {} } = a
            properties = omit(a, ['type', 'vertices', 'color', 'thickness'])
            if (color.hexCode) properties.stroke = color.hexCode
            if (isNum(a.thickness)) properties['stroke-width'] = a.thickness
            type = 'LineString'
            coordinates = a.vertices.map(b => [b.x, b.y, b.z || 0])
        } else if (polygonTypes.includes(a.type) && isArr(a.vertices)) {
            properties = omit(a, ['type', 'vertices'])
            type = 'Polygon'
            coordinates = [a.vertices.map(b => [b.x, b.y, b.z || 0])]
        } else {
            properties = a
        }

        return {
            type: "Feature",
            properties,
            geometry: {
                type,
                coordinates,
            }
        }
    }

    return {
        type: "FeatureCollection",
        features: json.entities.map(a => fmtFeature(a))
    }
}

module.exports = {
    toGeojson,
}
